package netty.c1.echoPractice;

import com.google.common.primitives.Chars;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.nio.charset.Charset;

/**
 * @author ChenweiLin
 * @create 2022-02-14 12:10
 */
public class EchoServer {
    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buffer = msg instanceof ByteBuf ? ((ByteBuf) msg) : null;
                                System.out.println(buffer.toString(Charset.defaultCharset()));

                                //思考：需要释放buffer吗
                                //答：不需要，tail节点会处理释放

                                //建议使用 ctx.alloc() 创建 ByteBuf
                                ByteBuf response = ctx.alloc().buffer(20);
                                response.writeBytes("hello,i am server".getBytes());
                                ctx.writeAndFlush(response);

                                //思考：需要释放response吗
                                //答：不需要，head节点会处理释放
                            }
                        });
                    }
                }).bind(8080);
    }
}
